<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/12
 * Time: 17:24
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\order;

use app\admin\controller\BaseController;
use app\common\library\OrderHelp;
use app\common\model\ChannelSender;
use app\common\model\SysCountries;
use app\common\model\Orders;
use app\common\service\orders\OrderService;
/**
 * 生成订单发票
 * Class InvoiceController
 * @package app\admin\controller\order
 */
class InvoiceController extends BaseController
{
    /**
     * 渲染模板
     * @date 2020/12/12
     * @author longli
     */
    public function render()
    {
        $ids = $this->request->get("ids");
        if(empty($ids)) $this->error("非法请求");
        $files = $error = [];
        foreach(Orders::with(['account.platform', 'detail'])->whereIn("order_id", $ids)->select() as $order)
        {
            $code = $order->account->platform->code;
            // 检查模板是否存在
            if(!view()->exists($code))
            {
                $error[$order->platform_name] = "【{$order->platform_name}】平台发票模板不存在";
                continue;
            }
            $country = SysCountries::getByCode($order->buyer_country_code);
            // 未设置国家税率
            if(!($taxRate = $country->tax_rate))
            {
                $error[$order->buyer_country_code] = "【{$order->buyer_country}】未设置税率";
                continue;
            }

            if(!($sender = ChannelSender::getByAccount($order->account_id))) $sender = ChannelSender::getDefault();
            if(empty($sender))
            {
                $error[$order->account_id] = "未配置发货地址";
                continue;
            }

            $this->assign("sender", $sender);
            $this->assign("sender_country", SysCountries::getByCode($sender->country_code));
            $this->assign("country", $country);
            $this->assign("tax_rate", $taxRate);
            $this->assign("calculate_rate", "1.{$taxRate}");
            $this->assign("order", $order);
            $html = $this->fetch($code)->getContent();
            $files[] = OrderService::getInstance()->generateInvoice($html, $order->order_no);
        }
        if(empty($files)) $this->error(join(", ", $error));
        if(count($files) == 1) $this->success("生成成功", '', ['path' => current($files)]);
        if(!($path = OrderHelp::compressFile($files))) $this->error("发票生成失败");
        $this->success("生成成功", '', ['path' => $path]);
    }
}